package com.ant.backstage.controller;

import com.alibaba.fastjson.JSONObject;
import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import com.ant.backstage.facade.dto.PowerDTO;
import com.ant.backstage.facade.dto.RoutesDto;
import com.ant.backstage.facade.dto.UserDTO;
import com.ant.backstage.facade.enums.TagTypeEnum;
import com.ant.backstage.facade.model.User;
import com.ant.backstage.facade.request.UpdateUserInfoRequest;
import com.ant.backstage.facade.request.power.PageUserInfoRequest;
import com.ant.backstage.facade.request.updateUserStatusRequest;
import com.ant.backstage.facade.response.PageFrontResponse;
import com.ant.backstage.facade.response.PageUserInfoResponse;
import com.ant.backstage.facade.response.vo.UserVo;
import com.ant.backstage.service.PermissionService;
import com.ant.backstage.service.UserService;
import com.ant.backstage.utils.DateUtil;
import com.ant.backstage.utils.RedisUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/v1/user")
public class UserContrlloer {

    private static Logger logger = LogManager.getLogger(UserContrlloer.class);

    @Resource
    UserService userService;
    @Resource
    PermissionService permissionService;
    @Resource
    MapperFacade mapperFacade;
    @Resource
    RedisUtil redisUtil;
    @Resource
    CommonMethod commonMethod;

    @ApiOperation(value = "查用户信息以及路由", response = ApiReturn.class)
    @RequestMapping(value = "/selectUser", method = RequestMethod.GET)
    public ApiReturn<UserVo> selectUser(@RequestParam(required = false) String uid, HttpServletRequest request) {
        logger.info("查用户信息入参 uid={}", uid);
        ApiReturn<UserVo> userApiReturn = new ApiReturn<>();
        UserDTO user = null;
        if (uid == null) {
            user = commonMethod.getUserInfoByToken(request);
        } else {
            User userByUid = userService.selectUserByUid(uid);
            user = mapperFacade.map(userByUid, UserDTO.class);
        }
        //用户的基本信息
        UserVo resultUser = mapperFacade.map(user, UserVo.class);
        resultUser.setCreatedatetime(DateUtil.format(user.getCreatedatetime(), DateUtil.YYYY_MM_DD_HHMMSS));
        //用户权限 路由
        List<RoutesDto> userPerList = permissionService.findUserPerByUid(user.getUid());
        List<JSONObject> jsonObjects = new ArrayList<>();
        //对象转json 前端展示需要
        userPerList.forEach(item -> {
            JSONObject jo = (JSONObject) JSONObject.toJSON(item);
            if (item.getAccess() == null || StringUtils.isBlank(item.getAccess())) {
                jo.remove("access");
            }
            if (item.getComponent() == null || StringUtils.isBlank(item.getComponent())) {
                jo.remove("component");
            }
            if (item.getIcon() == null || StringUtils.isBlank(item.getIcon())) {
                jo.remove("icon");
            }
            if (item.getName() == null || StringUtils.isBlank(item.getName())) {
                jo.remove("name");
            }
            if (item.getPath() == null || StringUtils.isBlank(item.getPath())) {
                jo.remove("path");
            }
            if (item.getRoutes() == null || item.getRoutes().isEmpty()) {
                jo.remove("routes");
            }
            jsonObjects.add(jo);
        });
        resultUser.setRouteList(jsonObjects);
        logger.info("查用户信息出参 uid={},resultUser={}", uid, JSONObject.toJSONString(resultUser));
        userApiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        userApiReturn.setData(resultUser);
        return userApiReturn;
    }

    @ApiOperation(value = "分页用户信息", response = PageFrontResponse.class)
    @RequestMapping(value = "/selectPageUser", method = RequestMethod.POST)
    public PageFrontResponse selectPageUser(@RequestBody PageUserInfoRequest pageUserInfoRequest) {
        logger.info("查分页用户信息 pageUserInfoRequest={}", JSONObject.toJSONString(pageUserInfoRequest));
        User user = mapperFacade.map(pageUserInfoRequest, User.class);

        PageInfo objectPageInfo = userService.selectPageUserInfo(user, pageUserInfoRequest.getPageNum(), pageUserInfoRequest.getPageSize());
        logger.info("查分页用户信息 objectPageInfo={}", JSONObject.toJSONString(objectPageInfo));
        PageFrontResponse pageFrontResponse = new PageFrontResponse();
        List<PageUserInfoResponse> pageUserList = new ArrayList<>();
        if (objectPageInfo == null) {
            pageFrontResponse.setResultMsg(ApiReturnCode.NO_TERM_DATAS.getMessage());
            pageFrontResponse.setResultCode(ApiReturnCode.NO_TERM_DATAS.getCode());
            return pageFrontResponse;
        }
        List<Map> list = objectPageInfo.getList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.stream().forEach(item -> {
            Map i = (Map) item;
            User user1 = (User) i.get("user");
            PageUserInfoResponse pageUserInfoResponse = mapperFacade.map(user1, PageUserInfoResponse.class);
            // 格式化时间
            pageUserInfoResponse.setCreatedatetime(sdf.format(user1.getCreatedatetime()));
            pageUserInfoResponse.setLastupdatetime(sdf.format(user1.getLastupdatetime()));

            List<PowerDTO> power = (List<PowerDTO>) i.get("power");
            pageUserInfoResponse.setPowerMap(power);
            pageUserList.add(pageUserInfoResponse);
        });
        logger.info("查分页用户信息 出参 objectPageInfo={}", JSONObject.toJSONString(objectPageInfo));

        pageFrontResponse.setData(pageUserList).setPageNum(objectPageInfo.getPageNum())
                .setPages(objectPageInfo.getPages()).setPageSize(objectPageInfo.getPageSize())
                .setTotal(objectPageInfo.getTotal());
        pageFrontResponse.setResultMsg(ApiReturnCode.SUCCESSFUL.getMessage());
        pageFrontResponse.setResultCode(ApiReturnCode.SUCCESSFUL.getCode());
        return pageFrontResponse;
    }

    @ApiOperation(value = "修改用户信息", response = ApiReturn.class)
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public ApiReturn updateUserInfo(@RequestBody UpdateUserInfoRequest updateUserInfoRequest) {
        logger.info("修改用户信息 入参 updateUserInfoRequest={}", JSONObject.toJSONString(updateUserInfoRequest));
        ApiReturn apiReturn = userService.updateUserInfo(updateUserInfoRequest);
        return apiReturn;
    }

    @ApiOperation(value = "修改用户状态", response = ApiReturn.class)
    @RequestMapping(value = "/updateStatus", method = RequestMethod.GET)
    public ApiReturn updateStatus(updateUserStatusRequest updateUserStatusRequest) {
        logger.info("修改用户状态 入参 updateUserStatusRequest={}", JSONObject.toJSONString(updateUserStatusRequest));
        ApiReturn apiReturn = userService.updateUserStatus(updateUserStatusRequest.getStatus(), updateUserStatusRequest.getUid());
        if (apiReturn.getCode().equals("200")) {
            //  由于用户状态被修改，用户饿认证信息,授权等，需要清除缓存
            boolean b = redisUtil.delPrefixStr(updateUserStatusRequest.getUid()); //根据前缀删除缓存
            Subject subject = SecurityUtils.getSubject();
            UserDTO user = (UserDTO) subject.getPrincipal();
            redisUtil.del(user.getToken()); //根据前缀删除缓存
        }
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        return apiReturn;
    }

    @ApiOperation(value = "获取用户详情", response = ApiReturn.class)
    @RequestMapping(value = "/selectUserInfo", method = RequestMethod.GET)
    public ApiReturn selectUserInfo(HttpServletRequest request) {
        logger.info("获取用户详情");
        UserDTO userPo = commonMethod.getUserInfoByToken(request);
        ApiReturn apiReturn = userService.selectUserInfo(userPo.getUid());
        return apiReturn;
    }

    @ApiOperation(value = "获取用户类型的展示标签", response = ApiReturn.class)
    @RequestMapping(value = "/getUserTagsList", method = RequestMethod.GET)
    public ApiReturn getUserTagsList() {
        logger.info("获取用户类型的展示标签");
        ApiReturn apiReturn = userService.selectTagsByType(TagTypeEnum.USER_TYPE.getCode());
        return apiReturn;
    }

}
